package com.java8.optional.learn;

import org.junit.Test;

import java.util.Optional;

/**
 * Optional类: 为了程序中避免出现空指针异常而创建的
 * 常用的方法: ofNullable(T t)
 *              orElse
 */
public class OptionalTest {


    /*
            Optional.of(T t): 创建一个Optional实例,t必须非空。
            Optional.empty(): 创建一个空的Optional实例。
            Optional.ofNullable(T t): t可以为null
     */
    @Test
    public void test1() {
        Girl girl = new Girl();
        //of(T t):这里不能传入null,如果传入会报空指针异常
        Optional<Girl> girlOptional = Optional.of(girl);

    }

    @Test
    public void test2() {
        Girl girl = new Girl();
        girl = null;
        //这里如果传入null,相当于调用了empty
        //ofNullable(T t): t可以为null
        Optional<Girl> girlOptional = Optional.ofNullable(girl);
        System.out.println(girlOptional);

        //orElse(T t): 如果当前的Optional内部封装的t是非空的,则返回内部的t。
        //如果内部的t是空的,则返回orElse()方法中的参数
        Girl girl1 = girlOptional.orElse(new Girl("赵丽颖"));
        System.out.println(girl1);

    }


    public String getGirlName(Boy boy) {
        return boy.getGirl().getName();
    }

    @Test
    public void test3() {
        Boy boy = new Boy();
        String girlName = getGirlName(boy);
        System.out.println(girlName);
    }


    //优化以后的方法
    public String getGirlNameOptional(Boy boy) {
        if (boy != null) {
            Girl girl = boy.getGirl();
            if (girl != null) {
                String name = girl.getName();
                if (name != null)
                    return girl.getName();
            }
        }
        return null;
    }

    @Test
    public void test4() {
        Boy boy = new Boy();
        String girlName = getGirlNameOptional(boy);
        System.out.println(girlName);
    }

    //使用的Optional类的getGirlName2()
    public String getGirlName2(Boy boy) {
        //此时的Boy1一定非空
        Boy boy1 = Optional.ofNullable(boy)
                .orElse(new Boy(new Girl("迪丽热巴")));

        Girl girl = boy1.getGirl();
        //此时的girl1一定非空
        Girl girl1 = Optional.ofNullable(girl)
                .orElse(new Girl("古力娜扎"));
        return girl1.getName();

    }

    @Test
    public void test5() {
        Boy boy = null;
        String girlName2 = getGirlName2(boy);
        System.out.println(girlName2);
    }

    /**
     * 4.isPresent():判断容器中是否包含值，用此方法可避免NoSuchElementException异常
     */
    @Test
    public void test6() {
        Optional<Object> objectOptional = Optional.ofNullable(null);
        if(objectOptional.isPresent()) {
            System.out.println(objectOptional.get());
        }
    }



}
